package GUILayer;

import javax.swing.*;
import javax.swing.border.TitledBorder;

import CtrLayer.SalesOrderCtr;
import ModelLayer.SalesOrder;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class OrderListUI extends JPanel {
	private JTextField txtFilter;
	private JScrollPane SalesOrderScrollPane;
	private JTable SalesOrderTable;
	
	private OrderListTableModel soTableModel;
	
	private SalesOrderCtr soCtr;

	public OrderListUI() {
		soCtr = SalesOrderCtr.getInstance();
		setLayout(null);

		JPanel panelTableModel = new JPanel();
		panelTableModel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Orders", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panelTableModel.setBounds(12, 13, 971, 343);
		add(panelTableModel);
		panelTableModel.setLayout(null);

		SalesOrderScrollPane = new JScrollPane();
		SalesOrderScrollPane.setBounds(12, 13, 947, 284);
		SalesOrderTable = new JTable();
		soTableModel = new OrderListTableModel();
		soTableModel.populateList();
		SalesOrderTable.setModel(soTableModel);
		SalesOrderScrollPane.setViewportView(SalesOrderTable);
		panelTableModel.add(SalesOrderScrollPane);

		JLabel lblFilter = new JLabel("Filter:");
		lblFilter.setHorizontalAlignment(SwingConstants.RIGHT);
		lblFilter.setBounds(12, 314, 85, 14);
		panelTableModel.add(lblFilter);
		
		txtFilter = new JTextField();
		txtFilter.setBounds(107, 310, 116, 22);
		panelTableModel.add(txtFilter);
		txtFilter.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent arg0) {
				filterSalesOrders();
			}
		});
		txtFilter.setColumns(10);
		
		JButton btnRemove = new JButton("Remove");
		btnRemove.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				deleteSalesOrder(SalesOrderTable.getSelectedRow());
			}
		});
		btnRemove.setBounds(505, 309, 97, 25);
		panelTableModel.add(btnRemove);
	}

	protected void deleteSalesOrder(int selectedRow) {
		if(selectedRow > -1)
		{
			soCtr.removeSalesOrder((int) SalesOrderTable.getModel().getValueAt(selectedRow, 0));
		}
		
	}

	protected void filterSalesOrders() {
		soTableModel.populateList(txtFilter.getText());

	}
}